package com.ccit.order.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccit.common.client.AreaClient;
import com.ccit.common.exception.GymException;
import com.ccit.model.Area;
import com.ccit.model.Order;
import com.ccit.order.mapper.OrderMapper;
import com.ccit.order.repository.OrderRepository;
import com.ccit.order.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

//    @Autowired
//    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private AreaClient areaClientService;

   /* @Autowired
    private UserClientService userClientService;*/

    //    @CacheEvict(value = "order", keyGenerator = "KeyGenerator")
    @Override
    public void saveNewOrder(Order order, Integer num) {
        order.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        //将消息携带绑定键值：DirectRouting 发送到交换机TestDirectExchange
        order.setTime(new Date());
        System.out.println(order);
//        rabbitTemplate.convertAndSend("OrderDirectExchange", "OrderDirectRouting", order);
//        rabbitTemplate.convertAndSend("OrderDirectExchange", "OrderDirectRouting", num);
        saveOrder(order);
    }


    //保存新订单
    @Override
    public Boolean saveOrder(Order order) {

        String areaName = order.getArea();
        System.out.println(order + "-------------");
        Area areaExist = areaClientService.getByName(areaName);
        if (areaExist != null) {
            Optional<Order> one = orderRepository.findById(order.getId());
            if (one != null && one.isPresent()) {
                Order orderExist = one.get();
                order.setTime(orderExist.getTime());
                Order save = orderRepository.save(order);
                if (save != null) {
                    return true;
                } else return false;
            } else {//订单不存在
                //会员判断
                /*User userExist = userClientService.getByPhone(order.getPhone());
                if (userExist != null){
                    order.setIsMember(1);
                }else {
                    order.setIsMember(0);
                }*/
                order.setTime(new Date());
                Order save = orderRepository.save(order);
                if (save != null) {
                    return true;
                } else return false;
            }
        } else {
            throw new GymException(202, "参数错误，无此场地");
        }

    }

    //根据id查询订单
    @Override
    public Order findOrderById(Long id) {
        Order order = orderRepository.findById(Long.toString(id)).get();
        return order;
    }

    //根据手机号查询订单
    @Override
    public List<Order> findOrderByPhone(String phone) {
        return orderRepository.findOrderByPhoneLike(phone);
    }

    //根据id删除订单
    @Override
    public void deleteOrderById(Long id) {
        orderRepository.deleteById(Long.toString(id));
    }


    //查询所有订单
    @Override
    public List<Order> findAllOrder() {
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        List<Order> all = orderRepository.findAll(sort);
        return all;
    }

    //条件查询订单
    @Override
    public List<Order> findOrderList(Order order) {
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        //构建条件
        Example<Order> orderExample = Example.of(order);
        List<Order> orderList = orderRepository.findAll(orderExample, sort);
        return orderList;
    }

    //模糊查询订单
    @Override
    public List<Order> findOrderLike(Order order) {
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);//改变默认大小写忽略方式：忽略大小写
        Example<Order> orderExample = Example.of(order);
        List<Order> orderList = orderRepository.findAll(orderExample, sort);
        return orderList;
    }

    //分页查询订单
    @Override
    public Page<Order> findOrderPage(Integer currPage, Integer pageSize, Order order) {
        if (currPage <= 0) {
            currPage = 1;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        Pageable pageable = PageRequest.of(currPage - 1, pageSize, sort);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //创建对象
        Example<Order> orderExample = Example.of(order, matcher);
        //调用方法实现查询
        Page<Order> orderPage = orderRepository.findAll(orderExample, pageable);
        return orderPage;
    }

    //根据手机号分页查询订单
    @Override
    public Page<Order> findOrderPageByPhone(Integer currPage, Integer pageSize, Order order) {
        if (currPage <= 0) {
            currPage = 1;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        Pageable pageable = PageRequest.of(currPage - 1, pageSize, sort);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true)
                .withMatcher("phone", ExampleMatcher.GenericPropertyMatchers.exact())
                .withIgnorePaths("time", "isMember", "area", "price");
        //创建对象
        Example<Order> orderExample = Example.of(order, matcher);
        //调用方法实现查询
        Page<Order> orderPage = orderRepository.findAll(orderExample, pageable);

        return orderPage;
    }

    //查找时间内的订单
    public List<Order> findOrderByTime(Date startTime, Date endTime) {
        return orderRepository.findOrderByTimeBetween(startTime, endTime);
    }


}
